package cc.mrbird.febs.common.datasource.starter.configure;

import cc.mrbird.febs.common.datasource.starter.organization.OrganizationHandler;
import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xufeng
 */
@Configuration
public class DataSourceAutoConfigure {

    /**
     * 分页插件
     * @param tenantHandler 租户处理器
     * @return PaginationInterceptor
     */
    @Bean
    @ConditionalOnMissingBean
    @Order(-2)
    public PaginationInterceptor paginationInterceptor(TenantHandler tenantHandler) {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        List<ISqlParser> sqlParserList = new ArrayList<>();
        TenantSqlParser organizationSqlParser = new TenantSqlParser();
        organizationSqlParser.setTenantHandler(tenantHandler);
        sqlParserList.add(organizationSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }

    /**
     * 创建租户维护处理器对象
     * @return 处理后的租户维护处理器
     */
    @Bean
    @ConditionalOnMissingBean
    public TenantHandler TenantHandler() {
        return new OrganizationHandler();
    }
}
